<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<link rel="stylesheet" type="text/css" href="http://192.168.1.192:8090/index-css.css"/>
		<link rel="stylesheet" type="text/css" href="http://192.168.1.192:8090/client_style.css"/>
		<link rel="stylesheet" type="text/css" href="http://192.168.1.192:8090/layui/css/layui.css" media="all"/>
		
		<link rel="stylesheet" type="text/css" href="http://192.168.1.192:8090/007tool.css"/><!-- 自定义样式 -->
		
		<script src="http://192.168.1.192:8090/jq.js" type="text/javascript" charset="utf-8"></script>
		<script src="http://192.168.1.192:8090/layui/layui.all.js" type="text/javascript" charset="utf-8"></script>
		<script src="http://192.168.1.192:8090/pako.min.js" type="text/javascript" charset="utf-8"></script>
		<script src="http://192.168.1.192:8090/util.js" type="text/javascript" charset="utf-8"></script> <!-- 自定义样式-->
		<script src="http://192.168.1.192:8090/path.js" type="text/javascript" charset="utf-8"></script>
	</head>
	
	<body>
		<!-- 操作区 -->
		<div class="layui-layout-left" style="background-color: #f7f7f7; width: 60%; height: 100%; left: 0px;height: 100%;overflow: hidden;max-height: 100vh;">
			
			<!-- 连接到服务器 -->
			<br>
			<div class="row-search">
				<div class="col-search">
					<div class="col-left">ip:</div>
					<div class="col-right"><input class="layui-input layui-input-style" style="width: 220px; display: inline;" type="text" id="ip" value="192.168.1.181" placeholder=""/></div>
				</div>
				<div class="col-search">
					<div class="col-left">port:</div>
					<div class="col-right"><input class="layui-input layui-input-style" style="width: 250px;  display: inline;" type="text" id="port" value="1952" placeholder=""/></div>
				</div>
			</div>
			<div class="row-search">
				<div class="col-search">
					<div class="col-left">osType:</div>
					<div class="col-right">
						<select name="osType" class="layui-select layui-input-style" style="width: 220px;  display: inline;">
							<option value="android">android</option>
							<option value="web">web</option>
							<option value="ios" selected="selected">ios</option>
						</select>
					</div>
				</div>
				<div class="col-search">
					<div class="col-left">token:</div>
					<div class="col-right">
						<input class="layui-input layui-input-style" style="width: 250px; display: inline;" type="text" id="token" value="6ebdcf9e98e7cc4b03a31b31e6a8a55e" placeholder="token到redis中获取"/>
					</div>
				</div>
				
			</div>
			<button class="btn clearDataArea" style="position: absolute;right: 8px;top: 18px;">清空</button>
			<button type="button" name="link" class="layui-btn layui-bg-green layui-btn-style" style="display: inline;" onclick="getConnection()">连接</button>
			<button type="button" name="quit" class="layui-btn layui-bg-red layui-btn-style" style="display: inline;" onclick="unLink()">断开</button>
			<button type="button" name="quit" class="layui-btn layui-bg-cyan layui-btn-style" style="display: inline;" onclick="tips()">小贴士</button>
			
				<div id="wySelect"  style="width: 50rem; min-height: 300px; overflow: hidden; border: 1px solid #009E94; margin: 21px auto;box-sizing: unset;">
					
					<div id="keep" style="width: 50rem;">
						<!-- 筛选订阅项 -->
						<div class="layui-form-item" style="padding-top: 13px;">
							<label class="layui-form-label">code</label>
							<div class="layui-input-inline">
							  <input type="text" name="codeDesc" placeholder="" autocomplete="off" class="layui-input layui-input-style" style="border-radius: 5px; width: 110px;">
							</div>
							
							<label class="layui-form-label" style="width: 120px;">dataType</label>
							<div class="layui-input-inline">
							  <input type="text" name="dataTypeDesc" placeholder="" autocomplete="off" class="layui-input layui-input-style" style="border-radius: 5px; width: 110px;">
							</div>
							
							<button class="layui-btn layui-btn-style" id="searchBtn">按条件筛选</button><hr />
						</div>	
						
						<!--工具栏-->
						<div class="layui-btn-group">
						  <button type="button" class="layui-btn layui-btn-style" id="add">
							<i class="layui-icon">&#xe654;</i>添加
						  </button>
						  <button type="button" class="layui-btn layui-btn-style" onclick="unBind()">
							<i class="layui-icon">&#xe640;</i>删除
						  </button>
						  <button type="button" class="layui-btn layui-btn-style" onclick="getOnlyLookPathArr()">
							<i class="layui-icon">&#xe605;</i>可视
						  </button>
						</div>
					</div>
					
					<div class="layui-table-div">
						<table class="layui-table" id="codeArea" style="width: 50rem;">
							<tr style="color: #fff; font-weight: bolder; font-size: 20px; background-color: #1c2f2e;">
								<td width="15%" height="25px"><input type="checkbox" class="all-chk"/></td>
								<td width="15%" height="25px">类型type</td>
								<td width="15%" height="25px">股票代码code</td>
								<td width="15%" height="25px">股票市场ts</td>
								<td width="25%" height="25px">订阅主题dataType</td>
								<td width="15%" height="25px">操作</td>
							</tr>
						</table>
					</div>
				</div>
			
		</div>
		
		<!-- 数据展示区 -->
		<div class="layui-layout-right"  style="background-color: #FFFFFF; width: 40%; height: 100%; max-height: 95vh;"><!-- id="dataArea" -->
			<h1>hey!bro</h1>
			
			<!-- 数据区：所有回包消息将追加到这来 -->
			<div id="dataArea" style=" word-wrap:break-word; height: 100%;overflow: auto; max-height: 95vh;">
				
			</div>
			
			<!-- 弹出层 -->
			<div id="showWindow" style="display: none;">
				
				<div style="margin-left: 40px;">
					<div id="#" style="font-size: 14px;">
						<table border="0px" style="margin-top: 20px;width: 700px; font-size: 14px;" >
							<tr>
								<td style="width: 100px;">type:</td>
								<td><input type="radio" name="type" id="" value=1 autocomplete="new-password"/>指数</td>
								<td><input type="radio" name="type" id="" value=2 checked="checked" autocomplete="new-password" />股票</td>
								<td><input type="radio" name="type" id="" value=3 autocomplete="new-password" />板块/概念行情</td>
								<td><input type="radio" name="type" id="" value=4 autocomplete="new-password" />行业涨跌幅</td>
								<td><input type="radio" name="type" id="" value=5 autocomplete="new-password" />市场涨跌统计</td>
							</tr>
						</table>
					</div>
				</div>

				<br>
				
				<div style="margin-left: 70px;">
					
					<!-- dataType订阅主题选择框 -->
					<div id="dataType">
						<label style="float: left;">dataType:</label>
						<div class="row-data div1"  style="border: 0px solid lightgray;width: 700px; height: 400px;padding-left: 52px; font-size: 14px;margin-left: 60px;background-color: #f7f7f7;"></div>
						<br>
					</div>
					
					<!-- 市场ts选择框 -->
					<div id="ts_div" style="font-size: 14px;">
						<table border="0px" style="margin-top: 20px;width: 620px; font-size: 14px;" >
							<tr>
								<td>ts:</td>
								<td><input type="radio" name="ts" id="" value="HK" checked="HK" autocomplete="new-password"/>HK</td>
								<td><input type="radio" name="ts" id="" value="US" autocomplete="new-password" />US</td>
								<td><input type="radio" name="ts" id="" value="SH" autocomplete="new-password" />SH</td>
								<td><input type="radio" name="ts" id="" value="SZ" autocomplete="new-password" />SZ</td>
							</tr>
						</table>
					</div>
					
					<br>
					
					<!-- 股票码code输入框 -->
					<div id="code_div">
						<label style="float: left;margin-left: 20px;">code:</label> 
						<input type="text" name="code" value="" id="code" placeholder="若type选行业涨跌幅，就填行业code" style="float: left; margin-left: 60px; width:643px"/>
					</div>
					
				</div>
			</div>
		</div>

	<script type="text/javascript">
		var ip;
		var port;
		var authFlag = false; //默认连接验证不通过
		var ws;
		
		var linkId;//用于关联主题tr和对应数据回包div的uuid
		var showFlag = false;
		
		var AUTH_PATH = Path.AUTH;//认证路径
		var OVER = "over";//结束标记
		var SUCCESS_CODE = "000000";//成功状态码(验证或订阅是否成功根据这个验证码判断)
		var TOPIC_BIND = Path.TOPIC_BIND; //在PathConstants类里
		var TOPIC_UNBIND = Path.TOPIC_UNBIND;
		var TOPIC_UNBINDALL = Path.TOPIC_UNBINDALL;
		
		var needToAppendArr = []; //需要追加到订阅table的主题集合
		var newToSubArr = [];   //用户每次选择要订阅的主题集合
		var unBindArr = []; //取消订阅的数组
		var rmTopicObj = {}; //删除主题对象
		var pathArr = []; //需要做可视的主题数组
		
		/* 清洗参数，移除多余的属性,用于订阅前的那个步骤 */
		function cleanTopic(arr){
			var newArr = [];
			for(i in arr){
				var topic = new Object();
				//code type 有特殊
				if(arr[i].code != ''){
					topic.code = arr[i].code;
					console.info(topic.code)
				}
				
				if(arr[i].type == '1' && arr[i].type == '2' && arr[i].type == '3'){
					topic.type = arr[i].type;
					console.info(topic.type)
				}
				
				topic.ts = arr[i].ts;
				console.info(topic.ts)
				topic.dataType = arr[i].dataType;
				console.info(topic.dataType)
				newArr.push(topic);
			}
			
			return newArr;
		}
		
		/* 添加订阅（弹出层） */
		$('#add').on('click', function(){
			
			var dataTypeCache = sessionStorage.getItem('allDataTypeArr');
			
			if(!authFlag){
				alert('您还没有进行认证，请认证后再进行操作!');
				return;
			}else{

				$.ajax({
					url: 'http://192.168.1.192:8090/api/stock/view/v1/getAllStockDataType',
					type: 'POST',
					dataType: 'json',
					crossDomain: true,
					async:false,
					contentType: 'application/json',
					success: function(msg){
						console.info('后台传回的数据：',msg)
						var arr = map2arr(msg);
						init(arr); //初始化弹出层数据数据，dataType默认展示股票和指数的dataType,ts默认是HK
					},
					error: function(msg){
						let data = {"14-1":"概念板块","2-8-1":"K线-1分钟-不复权","2-8-3":"K线-1分钟-后复权","2-8-2":"K线-1分钟-前复权","2-11-1":"K线-15分钟-不复权","9-1":"股票状态","10":"资金统计","2-14-2":"K线-120分钟-前复权","2-12-3":"K线-30分钟-后复权","2-14-1":"K线-120分钟-不复权","12":"市场涨跌统计","2-12-2":"K线-30分钟-前复权","2-10-3":"K线-5分钟-后复权","2-12-1":"K线-30分钟-不复权","9-8":"当前交易状态","15":"北向资金","16":"公共信息","2-16-2":"k线-盘后数据","2-14-3":"K线-120分钟-后复权","2-16-1":"k线-盘前数据","2-3-2":"K线-日K-前复权","2-1-3":"K线-盘后分时-不复权","2-3-1":"K线-日K-不复权","2-3-3":"K线-日K-后复权","2-1-2":"K线-盘前分时-不复权","2-1-1":"K线-分时-不复权","1":"详情","3":"盘口","4":"股价","5":"买卖盘，委托挂单","6":"买卖经纪席位","7":"逐笔成交","8":"成交统计","13-2":"行业涨跌幅","2-9-3":"K线-3分钟-后复权","13-1":"行业板块","2-9-2":"K线-3分钟-前复权","2-9-1":"K线-3分钟-不复权","2-10-2":"K线-5分钟-前复权","2-10-1":"K线-5分钟-不复权","2-13-3":"K线-60分钟-后复权","2-15-1":"K线-240分钟-不复权","2-13-2":"K线-60分钟-前复权","2-11-3":"K线-15分钟-后复权","2-13-1":"K线-60分钟-不复权","2-11-2":"K线-15分钟-前复权","2-15-3":"K线-240分钟-后复权","2-15-2":"K线-240分钟-前复权","2-2-1":"K线-五日-不复权"}
						let arr = map2arr(data);
						init(arr)
						// alert("ajax有误" + msg.readyState + "----" + msg.responseText);
					}
				 });
				 
				/* 弹出层 */ 
				layer.open({
					title: '订阅',
					type: 1,
					area: ['900px', '700px'],
					shadeClose: true, //点击遮罩关闭
					content: $("#showWindow"),
					btn: ['订 阅'],
					cancel: function(){
						$("input[name='type'][value=2]").prop('checked',true);
						$(".row-data").empty();
					},
					yes: function(index, layero){ //index是当前层索引，layero是当前层对象
					
						if(authFlag){
							
							//获取code、ts的div的展示状态，如果已经隐藏，则置空值
							var code_isShow = $("body #code_div").css('display');
							var ts_isShow = $("body #ts_div").css('display');
							
							var type = '';
							var code = '';
							var ts = '';
							
							if(code_isShow == 'block'){
								
								tempCode = $("body input[name='code']").val();
								code = myToUppercase(tempCode);
								//code = $("body #layui-layer1").find("input[name='code']")[0].value;
								console.info("code：" + code);
							}
							
							if(ts_isShow == 'block'){
								//获取ts
								ts = $("body input[name='ts']:checked").val();
								console.info("ts：" + ts);
							}
							
							//获取所有被选中的dataType
							var tempArr = $("body input[name='dataType']:checked");
							console.info('本次被选中的dataType集合' , tempArr)
							
							
							var tempType = $("body input[name='type']:checked").val();
							
							if(tempArr.length == 0 && (tempType == 1|tempType == 2 | tempType == 4)){
								
								if(code == "" || code == undefined){
									alert("你还没有勾选dataType！没有输入code！");
									//layer.closeAll();
									return;
								}
							
							}else if(tempType == 1|tempType == 2 | tempType == 4){
								if(code == "" || code == undefined){
									alert("没有输入code！")
									//layer.closeAll();
									return;
								}
							}else if(tempArr.length == 0){
								alert("你还没有勾选dataType！");
								//layer.closeAll();
								return;
							}
							
							if(tempType == "4" | tempType == "5"){
								type = '';
							}else{
								type = tempType;
								console.info("type：" + type);
							}
							
							

							var param;
							
							newToSubArr = [];//先置空
							
							//获取并封装将要订阅的主题
							tempArr.each(function(i){
								var ss = $(this).val();
								var dataType = ss.substr(0, ss.length-1); //去掉dataType值后面的斜杆
								
								param = new Object();
								param.ts = ts;
								param.code = code;
								param.type = type;
								param.dataType = dataType;
								newToSubArr.push(param);
							}); 
							console.info('拟定要订阅的主题(未去重):',newToSubArr);
						
							var subedArr = getSubedArrByKey(ip + ":" + port + ':subedTopics');
							console.info('从缓存取出的已订阅的主题：',subedArr);
							
							//根据缓存中是否存在已订阅主题，确定是否要去重
							if(subedArr != null){
								needToAppendArr = getArrNeedToAppend(newToSubArr, subedArr, 'ts', 'code', 'type', 'dataType');
								console.info('needToAppendArr:' ,needToAppendArr);
								if(needToAppendArr.length != 0){
									//订阅主题
									var arr = cleanTopic(needToAppendArr);
									bindTopic(arr);
								}else{
									//如果本轮订阅的包含重复主题
									console.info('PS: 你刚刚的订阅中包含着重复主题，但是不用担心,我们已经去重了')
									layer.closeAll();
									$(".row-data").empty();//清空弹出层原来的datatype
									$('input[name="code"]').css('display','show');
									
								}
							}else{
								//如果没有缓存，那么订阅一定不会重复,可以直接订阅
								needToAppendArr = newToSubArr;
								var arr = cleanTopic(needToAppendArr);
								bindTopic(arr);
							}
						}else{
							alert("您尚未连接验证成功，没有权限订阅")
						}
						
					}
				});				  
			}
		});
		
		/* 点击dataType周边的文字也能勾选CheckBox */
		$(document).on('click', "body .checkDataType", function() {
			$(this).parent().find("input").trigger("click");
		});
		
		
		/* 初始化弹窗面板 */
		function init(arr){
			sessionStorage.setItem('allDataTypeArr', JSON.stringify(arr)); // 所有的dataType存入缓存
			$("input[name='type'][value = 2]").prop('checked', true);
			$("input[name='ts'][value = 'HK']").prop('checked', true);
			$("#code_div").css('display', 'block');
			var resArr = getDataTypeByType(2, arr);
			addDataType(resArr);
		}
		
		/* 让dataType的展示随type改变 */
		$(document).on('click', 'input[name=type]', function() {
			var arr = JSON.parse(sessionStorage.getItem("allDataTypeArr"));
			var type = $(this).val(); //获取到被选中内容
			var resArr = getDataTypeByType(type, arr); //获取对应的数组
			
			//根据type隐藏相应的元素
			$(".row-data").empty();//先清空HTML
			addDataType(resArr); //再追加
			
			if(type == 1 | type == 2){
				$("body #code_div").css('display','show');//指数、股票
			}else if(type == 3){
				$("body #code_div").css('display','none');//板块，概念行情 
			}else if(type == 4){
				$("body #code_div").css('display','show');//行业涨跌幅，不用传type到后台
			}else if(type == 5){
				$("body #code_div").css('display','none');//市场涨跌幅
			}
		});
		
		/* 断开连接 */
		function unLink(){
			
			if(ws && ws.readyState == 1){
				ws.close();
				sessionStorage.clear();//清空缓存
				//location.reload();
			}
		}
		
		/* 判断当前字符串是否是字母字符串，如果是，则全部转成大写字母 */
		function myToUppercase(str){
			var upperCaseStr;
			if(isNaN(str)){
				upperCaseStr = str.toUpperCase();
				return upperCaseStr;
			}
			return str;
		}
		
		
		/* 小贴士 */
		function tips(){
			alert("+++ 三大市场port +++"+ "\n\n" +"美股port：1951" + "\n" + "A股port： 1950" + "\n" + "港股port：1952"+ "\n\n" + 
			"+++ 各环境ip +++" + "\n\n" + "dev环境：192.168.1.181" + "\n" + "test环境：192.168.1.241"+ "\n\n" + 
			"+++ 主要问题解答 +++" + "\n\n" + "①如果认证失败，请检查当前token是否失效、是否是对应环境对应平台的token；" + "\n\n" + 
			"②连接突然断开，刷新重连即可" + "\n\n" + 
			"③订阅完成后不会立即推送数据，要勾选对应订阅项点击'可视'才行" + "\n\n" + 
			"④F12一下，挖掘更多内容"  + "\n\n" + 
			"⑤有疑惑/建议/吐槽的兄dei请找 qinlingling");
		}
		
		/* 获取连接*/
		function getConnection(){
			if('WebSocket' in window){
				ip = $("#ip").val();
				port = $("#port").val();
				var url = "ws://" + ip + ":" + port;
				
				addTimeTag("客户端正在连接");
				ws = new WebSocket(url);
				
				// 建立连接
				ws.onopen  = function(){
					ws.binaryType = 'arraybuffer';//设置以二进制的方式发送
					addTimeTag('连接成功');
					sendAuth();
					ping();
					addTimeTag('自己：ping')
				};
				
				// 接收包
				ws.onmessage = function (evt){
				   var msg = evt.data;
				   //解压
				   var unzipStr = unzip(msg);
				   //byte数组转字符串
				   var str = byteToString(unzipStr);
				   console.log("回包数据体:",str);
				   
				   if(str == OVER){
					   ws.close();
					   addTimeTag('连接断开');
				   }else if(str == 'pong'){
					   addTimeTag('服务器：pong');
				   }else if(str == 'ping'){
					   addTimeTag('服务器：ping');
					   ws.send(zip('pong'))
				   }else{
					   var jsonObj = JSON.parse(str);
					   var responce = jsonObj;   
				   
						//responce 可能是请求包，也可能是回包（回包具备的属性：code、msg、path、respId/reqId、data）
						if(responce && responce.header&& responce.header.reqId){ //ws服务端订阅推送回包
							
							if(showFlag && belongsToPathArr(responce)){
								
								//解析拿到数据包中的Path
								//拿到全局的pathArr相比对
								// 如果相等则放行，追加
								addTimeTag('');
								$("#dataArea").append('<div class="dataDiv">' + str + '</div>');//追加消息到面板
							}
							
						}else if(responce.respId){  //请求回包
							
							var code = responce['code'];
							var path = responce['path'];
							
							//区分回包是订阅异常、订阅成功、认证成功、认证失败
							if(code && (SUCCESS_CODE == code) && (AUTH_PATH == path)){
								addTimeTag('认证成功')
								authFlag = true;
								$(".row-data").empty();
							}else if(code && !(SUCCESS_CODE == code) && (AUTH_PATH == path)){
								addTimeTag('认证失败'+'msg:'+ responce.msg +' code：' + responce.code)
							}else if(code && (SUCCESS_CODE == code) && (TOPIC_BIND == path)){
								
								addTimeTag('订阅成功');
								updSubedCache(needToAppendArr); //更新缓存
								if(needToAppendArr.length != 0){  //把已订阅的主题追加至显示板table
									addToTable(needToAppendArr);
								}
								console.info('缓存被更新了:', getSubedArrByKey(ip + ":" + port + ':subedTopics'))
								layer.closeAll();
								
								$(".row-data").empty();//清空弹出层原来的datatype
								
							}else if(code && (SUCCESS_CODE == code) && (TOPIC_UNBIND == path)){
								addTimeTag('取消订阅成功'+'msg:'+ responce.msg +' code：' + responce.code);
								delUnBindFromCache(unBindArr);//清缓存
								unBindArr = [];
								rmItem();//取消订阅成功后移除table上的对应项tr
							}else{
								addTimeTag(str);
								layer.closeAll();
								$(".row-data").empty();//清空弹出层原来的datatype
							}
						}else{
							console.log("异常回包体:",responce);
							layer.closeAll();
							$(".row-data").empty();//清空弹出层原来的datatype
						}						   
				   }
					
				}
				/* 监听到ws被关闭时 */
				ws.onclose = function(){
					alert('本次连接正在断开，请刷新重连！')
					//location.reload();
					sessionStorage.clear();//清空缓存
				};
			}else{
				alert("您的浏览器不支持websocket");
			}
		}
		
		/* 订阅主题,参数arr在弹出层传入 */
		function bindTopic(arr){
			
			var topicObj = createTopicMessage(arr,TOPIC_BIND);
			
			//转成字符串
			var topicStr = JSON.stringify(topicObj);
		
			//压缩
			var zipStr = zip(topicStr);
			//发送订阅
			ws.send(zipStr);
			
		}
		
		/* 构造要订阅的主题,arr是弹出层做好去重的arr */
		function createTopicMessage(arr,path){
			console.info('本次订阅的主题', arr)
			//构造订阅请求request
			var request = new Object();
			var header = new Object();
			var body = {};
			
			//构造header
			header.language = 'ZN';
			header.reqId = generateUUID();
			header.version = '1.0.0';
			//header.path = TOPIC_BIND;topic.unBind
			header.path = path;
			request.header = header;
			
			//构造订阅主题对象subTopic
			var subTopic = new Object();
			var topics = arr;
			
			subTopic.topics = topics;
			request.body = subTopic;
			
			return request;
		}
		
		/* 身份校验 */
		function sendAuth(){
			
			//构造request
			var request = new Object();
			var header = new Object();
			var body = new Object();
			
			//构造header
			header.language = 'ZN';
			header.reqId = generateUUID();
			header.version = '1.0.0';
			header.path = 'auth.auth';
			
			request.header = header;
			
			//构造body
			var timestamp = 1598942931965;
			var devId = '9c9595b9-ee21-4dff-ac31-acd76ab77ffe';
			var osType = $("select[name='osType'] option:selected").val();
			var token = 'd4f009dce36b80808db800f313fb0e89'
			console.info("token:", token);
			body.deviceId= devId;
			body.timestamp= timestamp;
			body.token= token;
			// body.osType= osType;
			
			request.body = body;
			
			//将request转成json字符串
			var json = JSON.stringify(request);
			
			var compressService = "gzipCompressService"; //gzipCompressService
			
			//压缩
			var zipStr = zip(json);
			
			ws.send(zipStr);
		}
		
		function pong(){
			setInterval(function(){
			   ws.send(zip('pong'));
			   console.log("自己:pong");
			},30000);
		}
		
		function ping(){
			setInterval(function(){
				
				if(ws.readyState != 3){
					ws.send(zip('ping'));
					addTimeTag("自己：ping")
				}
			},30000);
		}
		
		function isAuth(){
			if(!authFlag){
				alert('您还没有进行认证，请认证后再进行操作!');
				return;
			}
		}
		
		/* 刷新时清空缓存 */
		window.onload = function () { 
			sessionStorage.clear();
		}
		
		/* 移除被选中的tr */
		function removeItem(){
			console.info($(':checkbox:checked').closest('tr'));
			//$(':checkbox:checked').closest('tr').remove();
			$('input[class="chk"]:checked').closest('tr').remove();//通过class控制移除tr
		}
		
		/* 设置获取需要做可视的主题 */
		function getOnlyLookPathArr(){
			var trArr = $('input[class="chk"]:checked').closest('tr');//根据class取到所有被选中的行
			if(trArr.length  > 0){
				showFlag = true;//把全局的控制数据区是否追加的flag置true
				pathArr = [];
				for(var i=0;i<trArr.length;i++){
					var tr_id = $(trArr[i]).attr('tr_id');
					console.info('tr上的自定义属性：', tr_id)
					var arr = tr_id.split(':');
					var dataType = arr[arr.length-1];
					var path = Path.getPathByDataType(dataType);
					console.info('截取到的path:', path);
					pathArr.push(path);
				}
			}else{
				showFlag = false;
				pathArr = [];
			}
			console.info('本次设置可视的主题：',pathArr)
		}
		
		/* 设置数据区只展示已选定的主题数据,jsonObj是后端返回的数据包的json对象格式 */
		function belongsToPathArr(jsonObj){
			var pathStr = jsonObj.header.path;
			console.info('从订阅回包中获取到的参数path', pathStr);
			// for(i in pathArr){
			// 	if(pathArr[i] == pathStr){
			// 		return true;
			// 	}
			// }
			return pathArr.indexOf(pathStr)>-1;
		}
		
		/* 获取要取消的订阅，返回unBindArr */
		function getUnBindArr(){
			var trArr = $('input[class="chk"]:checked').closest('tr');//根据class取到所有被选中的行
			var needToUnBindArr = [];
			
			var trlength = trArr.size();
			//获取tr中的下标为1——4的td的text值，这与type，code，ts, dataType这几个参数一一对应
			for(var i = 0; i<trlength;i++){
				var type = $(trArr[i]).find('td').eq(1).text().trim();
				var code = $(trArr[i]).find('td').eq(2).text().trim();
				var ts = $(trArr[i]).find('td').eq(3).text().trim();
				var dataType = $(trArr[i]).find('td').eq(4).text().trim();
				
				var topic = getTopic(type, code, ts, dataType);
				console.info('取消订阅的主题', topic);
				needToUnBindArr.push(topic);
			}
			unBindArr = needToUnBindArr;
			return unBindArr;
		}
		
		/* 接收参数，构造并返回一个topic */
		function getTopic(type, code, ts, dataType){
			
			var param = new Object();
			
			switch(ts){
				case 'HK':
					param.ts = 'HK';
					break;
				case 'US':
					param.ts = 'US';
					break;
				case 'SZ':
					param.ts = 'SZ';
					break;
				case 'SH':
					param.ts = 'SH';
					break;
			}
			
			if(code != '- - -'){
				param.code = code;
			}
			
			switch(type){
				case '指数':
					param.type = '1';
					break;
				case '股票':
					param.type = '2';
					break;
				case "板块行情/概念行情":
					param.type = '3';
					break;
			}
			
			var dataTypeValue = getDataTypeValueByDesc(dataType);
			param.dataType = dataTypeValue;
			
			return param;
		}
		
		/* 取消订阅 */
		function unBind(){
			
			var unBindArr = getUnBindArr();
			var topicObj = createTopicMessage(unBindArr,TOPIC_UNBIND);
			
			var topicStr = JSON.stringify(topicObj);//转成字符串
			var zipStr = zip(topicStr);//压缩
			ws.send(zipStr);//发送订阅
		}
		
		/**
		 * 删除单个订阅主题
		 */
		function removeTopic(obj){
			var unBindObj = $(obj).data("topic");
			if(unBindObj == '' || unBindObj == undefined){
				alert("出现错误");
				return;
			}
			var arr = unBindObj.split(",");
			var unArr = [];
			var unObj = {};
			if(arr[0] != '' && arr[0]<=3){ // type
				unObj.type=arr[0];
			}
			if(arr[1]!=''){//code
				unObj.code = arr[1];
			}
			unObj.ts=arr[2];
			unObj.dataType=arr[3];
			unArr.push(unObj);
			var topicObj = createTopicMessage(unArr,TOPIC_UNBIND);
			unBindArr = unArr;
			rmTopicObj = $(obj);
			var topicStr = JSON.stringify(topicObj);//转成字符串
			var zipStr = zip(topicStr);//压缩
			ws.send(zipStr);//发送订阅
		}
		
		/**
		 * 删除单项
		 */
		function rmItem(){
			if(!$.isEmptyObject(rmTopicObj)){
				rmTopicObj.parents("tr").remove();
				rmTopicObj = {};
			}else{
				removeItem();
			}
		}
		
		/* 按code和dataType筛选订阅项 ，做隐藏显示*/
		function selectBycodeAndDataType(){
			
			var dataTypeDesc = $('input[name="dataTypeDesc"]').val().trim();
			var codeDesc = $('input[name="codeDesc"]').val().trim();

			if(dataTypeDesc == '' && codeDesc == ''){
				$(".chk").closest('tr').css('display', 'show');//.closest('tr').

			}else{
				$(".chk").closest('tr').css('display', 'none');
				// if(dataTypeDesc != '' && dataTypeDesc != undefined && codeDesc != '' && codeDesc != undefined){
				// 	$("tr").filter(":contains("+dataTypeDesc"+):contains("+codeDesc+"):has(.chk)").css('background','#b8dac2');
				// }
				let filterArg = '' 
				filterArg += dataTypeDesc?`:contains(${dataTypeDesc})`: '';
				filterArg += codeDesc?`:contains(${codeDesc})`: '';
				filterArg += `:has(".chk")`
				//$("tr").css('background','#fff');
				if (dataTypeDesc || codeDesc) {
					console.log('filterArg:', filterArg)
					
					//$("tr").filter(filterArg).css('background','#b8dac2');
					$("tr").filter(filterArg).css('display', 'show');
				}
			}
			
		}
		

		
		$(function(){ 
			/* 清空数据区 */
			$(".clearDataArea").click(function(){
				
				$("#dataArea").empty();
			})
			
			
			/* 全选全不选 */
			$('.all-chk').change(function(){
				//alert($('.all-chk').prop('checked')); true/false
				
				if($('.all-chk').prop('checked') == true){
					$('.chk').prop('checked', true);
				}else{
					$('.chk').prop('checked', false);
				}
			});
			
			/* 动态追加的元素不能直接绑定，但可以通过他的外层元素（已存在的元素）绑定自身 */	
			$('#codeArea').on('click', '.chk', function() {
				$(".all-chk").prop('checked',$(":checkbox[class='chk']:checked").length == $(":checkbox[name='chk']").length);
			})
			
			/* 多条件筛选 */
			$('#searchBtn').click(function(){
				selectBycodeAndDataType()
			})
		});
	</script>

	</body>
</html>
